<template>
  <div class="card-management">
    <!-- 搜索区域 -->
    <el-card shadow="hover" class="search-box">
      <el-form inline :model="searchForm">
        <el-form-item label="卡名">
          <el-autocomplete
            v-model="searchForm.cardName"
            :fetch-suggestions="suggestionsCard"
            placeholder="请输入卡名"
            clearable
          />
        </el-form-item>
        <el-form-item label="仓库名称">
          <el-autocomplete
            v-model="searchForm.warehouseName"
            :fetch-suggestions="suggestionsWarehouse"
            placeholder="请输入仓库名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="关键词">
          <el-input v-model="searchForm.key" placeholder="请输入关键词" clearable/>
        </el-form-item>
        <el-form-item label="进价范围">
          <el-input-number v-model="searchForm.minCostPrice" :min="0" placeholder="最低价" clearable/>
          -
          <el-input-number v-model="searchForm.maxCostPrice" :min="0" placeholder="最高价" clearable/>
        </el-form-item>
        <el-form-item label="售价范围">
          <el-input-number v-model="searchForm.minPrice" :min="0" placeholder="最低价" clearable/>
          -
          <el-input-number v-model="searchForm.maxPrice" :min="0" placeholder="最高价" clearable/>
        </el-form-item>
        <el-form-item label="购买时间">
          <el-date-picker
            v-model="searchForm.BuyTime"
            type="daterange"
            value-format="YYYY-MM-DD"
            range-separator="-"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            clearable
          />
        </el-form-item>
        <el-form-item label="售出时间">
          <el-date-picker
            v-model="searchForm.soldTime"
            type="daterange"
            value-format="YYYY-MM-DD"
            range-separator="-"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            clearable
          />
        </el-form-item>
        <el-button type="primary" @click="loadCards">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>

      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <div class="operation-buttons">
      <el-button type="primary" @click="showAddDialog">添加卡片</el-button>
    </div>

    <!-- 卡片表格 -->
    <el-table :data="tableData" border stripe style="width: 100%">
      <el-table-column prop="cardId" label="编号" />
      <el-table-column prop="cardName" label="卡名" width="120"/>
      <el-table-column prop="warehouseName" label="仓库" width="120"/>
      <el-table-column prop="rarity" label="稀有度" width="80"/>
      <el-table-column prop="origin" label="来源" width="80"/>
      <el-table-column prop="batch" label="卡盒" width="80"/>
      <el-table-column prop="costPrice" label="进价" width="100"/>
      <el-table-column prop="price" label="售价" width="100"/>
      <el-table-column prop="buyTime" label="购买时间" width="100"/>
      <el-table-column prop="condition" label="状态" width="200"/>
      <el-table-column label="销售状态" width="120">
        <template #default="{row}">
          <el-tag :type="row.soldTime ? 'success' : 'danger'">
            {{ row.soldTime ? row.soldTime.toLocaleString() +'售出' : '在售中' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="{row}">
          <el-button size="small" @click="SaleStatus(row)">
            {{ row.soldTime ? '设为在售' : '设为已售' }}
          </el-button>
          <el-button size="small" type="danger" @click="handleDelete(row.cardId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogType === 'add' ? '添加卡片' : '编辑卡片'">
      <el-form :model="formData" label-width="100px" :rules="formRules">
        <el-form-item label="卡名" prop="cardmate">
          <el-select
            v-model="formData.cardmate"
            filterable
            remote
            reserve-keyword
            placeholder="请选择卡名"
            remote-show-suffix
            :remote-method="cardOptionsQuery"
            :loading="cardOptionsLoading"
            style="width: 240px"
          >
            <el-option
              v-for="item in cardOptions"
              :key="item.id"
              :label="item.id + ' '+item.cardname + ' - ' + item.rarity + ' - ' + item.origin + ' - ' + item.batch"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="仓库" prop="warehouseName">
          <el-select
            v-model="formData.warehouseName"
            filterable
            remote
            reserve-keyword
            placeholder="请选择仓库"
            remote-show-suffix
            :remote-method="warehouseOptionsQuery"
            :loading="warehouseOptionsLoading"
            style="width: 240px"
          >
            <el-option
              v-for="item in warehouseOptions"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="进价" prop="costPrice">
          <el-input-number v-model="formData.costPrice" :min="0"/>
        </el-form-item>
        <el-form-item label="售价" prop="price">
          <el-input-number v-model="formData.price" :min="0"/>
        </el-form-item>
         <el-form-item label="信息" prop="condition">
          <el-input
            v-model="formData.condition"
            type="textarea"
            :rows="4"
            placeholder="请输入卡片信息"
          />
         </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { selectCard, insertCard, deleteCard, toggleSaleStatus,selectCardmate,selectWarehouseName } from '@/api/card'

// 表格数据
const tableData = ref([])

// 搜索表单
const searchForm = ref({
  cardName: null,
  warehouseName: null,
  key: null,
  minCostPrice: null,
  maxCostPrice: null,
  minPrice: null,
  maxPrice: null,
  BuyTime: null,
  soldTime: null
})

//卡片种类相关
const cardOptions = ref([])
const cardOptionsLoading = ref(false)
const cardOptionsQuery = (quer)=>{
  cardOptionsLoading.value = true
  selectCardmate(quer).then(res => {
    if(res.data.code === 200){
      console.log("读取完成"+JSON.stringify(res.data.data))
      cardOptions.value = res.data.data;
    }else{
      ElMessage.error(res.data.msg)
    }
    cardOptionsLoading.value = false
  })
}
const suggestionsCard=  (quer,cb)=>{
  selectCardmate(quer).then(res => {
    if(res.data.code === 200){
      let set=new Set()
      res.data.data.forEach(item=>{
        set.add(item.cardname)
      })
      let re=[];
      Array.from(set).forEach(item=>{
        re.push({value:item})
        console.log("读取完成："+item)
      })
      console.log("读取完成："+JSON.stringify(re))
      cb(re)
      return;
    }else{
      ElMessage.error(res.data.msg)
    }
    cb([])
  })
}

//仓库相关
const warehouseOptions = ref([])
const warehouseOptionsLoading = ref(false)
const warehouseOptionsQuery = (quer)=>{
  warehouseOptionsLoading.value = true
  selectWarehouseName(quer).then(res => {
    if(res.data.code === 200){
      console.log("读取完成"+res.data.data)
      warehouseOptions.value = res.data.data;
    }else{
      ElMessage.error(res.data.msg)
    }
    warehouseOptionsLoading.value = false
  })
}
const suggestionsWarehouse=  (quer,cb)=>{
  selectWarehouseName(quer).then(res => {
    if(res.data.code === 200){
      console.log("读取完成"+res.data.data)
      let re=[];
      res.data.data.forEach(item=>{
        re.push({value:item})
      })
      cb(re)
      return;
    }else{
      ElMessage.error(res.data.msg)
    }
    cb([])
  })
}



// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add')
const formData = ref({
  cardmate:null,
  warehouseName: '',
  condition: '',
  costPrice: 0,
  price: 0,  
})
const formRules = {
  cardmate: [
    { required: true, message: '选择卡名', trigger: 'blur' }],
  warehouseName: [
    { required: true, message: '请输入仓库名称', trigger: 'blur' }],
  costPrice: [
    { required: true, message: '请输入进价', trigger: 'blur' }],
  price: [
    { required: true, message: '请输入售价', trigger: 'blur' }]
}

// 加载卡片数据
const loadCards = () => {
  console.log("搜索条件"+JSON.stringify(searchForm.value))
  selectCard({
    cardName: searchForm.value.cardName,  
    warehouseName: searchForm.value.warehouseName,
    key: searchForm.value.key,
    minCostPrice: searchForm.value.minCostPrice,
    maxCostPrice: searchForm.value.maxCostPrice,
    minPrice: searchForm.value.minPrice,
    maxPrice: searchForm.value.maxPrice,
    minBuyTime: searchForm.value.BuyTime? searchForm.value.BuyTime[0] : null,
    maxBuyTime: searchForm.value.BuyTime? searchForm.value.BuyTime[1] : null,
    minSoldTime: searchForm.value.soldTime? searchForm.value.soldTime[0] : null,
    maxSoldTime: searchForm.value.soldTime? searchForm.value.soldTime[1] : null,
  }).then(res => {
    if(res.data.code === 200){
      console.log("读取完成"+res.data.data)
      tableData.value = res.data.data;
    }else{
      ElMessage.error(res.data.msg)
    }
  })
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    cardName: null,
    warehouseName:null,
    key: null,
    minCostPrice: null,
    maxCostPrice: null,
    minPrice: null,
    maxPrice: null,
    BuyTime: null,
    soldTime: null
  }
  loadCards()
}


// 显示添加对话框
const showAddDialog = () => {
  dialogType.value = 'add'
  dialogVisible.value = true
  formData.value = {
    cardmate:null,
    warehouseName: '',
    condition: '',
    costPrice: 0,
    price: 0,  
  }
}


// 提交表单
const submitForm = () => {
    if(dialogType.value === 'add'){
      insertCard(formData.value).then(res => {
        if(res.data.code === 200){
          ElMessage.success('添加成功')
          dialogVisible.value = false
          loadCards()
        }else{          
          ElMessage.error(res.data.msg)
        }
      })
    }else{
      updateCard(formData.value).then(res => {
        if(res.data.code === 200){
          ElMessage.success('修改成功')
          dialogVisible.value = false
          loadCards()
        }else{          
          ElMessage.error(res.data.msg)
        }
      })
    }
}

// 删除卡片
const handleDelete = (cardId) => {
  console.log("删除卡片"+cardId)
  ElMessageBox.confirm('确定要删除该卡片吗？', '提示', { type: 'warning' }).then(() => {
    deleteCard(cardId).then(res => {
      if(res.data.code === 200){
        ElMessage.success('删除成功')
        loadCards()
      }else{          
        ElMessage.error(res.data.msg)
      }
    })
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}


// 切换销售状态
const SaleStatus = (row) => {
  toggleSaleStatus(row).then(res =>{
    if(res.data.code === 200){
      ElMessage.success('修改成功')
      loadCards()
    }else{          
      ElMessage.error(res.data.msg)
    }   
  })
}

onMounted(() => {
  loadCards()
})
</script>

<style scoped>
.card-management {
  padding: 20px;
}
.search-box {
  margin-bottom: 20px;
}
.operation-buttons {
  margin-bottom: 20px;
}
.el-pagination {
  margin-top: 20px;
  justify-content: flex-end;
}
</style>